<template> 
    <div class="up-file" v-if="type==='button'">
        <span>导入</span>
        <input type="file" :accept="accept" @change="upfile" />
    </div>
    <div class="up" v-if="type=='box'">
        <img v-if="fileUrl && isImg" :src="imgUrl" class="avatar" />
        <span v-else-if="fileUrl && !isImg" class="avatar-uploader-file"></span>
        <span v-else class="avatar-uploader"></span>
        <input type="file" :accept="accept" @change="upfile" />
        <span class="up_del" v-show="fileUrl" @click="del"></span>
        <div class="progress" v-show="progressFlag">
            <span><u :style="'width:'+loadProgress"></u></span>
            <i>{{loadProgress}}</i>
        </div>
    </div>
</template>

<script setup>
import { reactive,getCurrentInstance,toRefs,computed,toRaw,watch } from 'vue'
let { proxy } = getCurrentInstance()
const emit = defineEmits(['update:file','upload']) //此处要完全对应，采用固定的update:prop属性

const props = defineProps({
    type: { type: String, default: 'box' },//box button
    accept: { type: Array, default: ['image/jpeg','image/png','image/gif'] },
    debug: { type: Boolean, default: false },
    file: { type: String, default: "", require: true },
    dir: { type: String, default: "" },
    maxsize: { type: Number, default: 1024 * 1024 * 5 }, //单位K，默认5120K，即5M
    maxwidth: { type: Number, default: 0 },
    maxheight: { type: Number, default: 0 },
    background: { type: String, default: "" },
})

let isUpload = false //默认没上传过
let obj = reactive({
    fileUrl: props.file,
    progressFlag: false,
    loadProgress: "0%"
})
let imgUrl = computed(() => {
    if(!isUpload && fileUrl.value != ""){ //没上传过，且传入值不为空，表示这是默认值
        return proxy.$setting.globalUrl.fileurl+'/'+props.dir+'/'+fileUrl.value
    }
    if (isUpload && fileUrl.value != ""){ //上传过，且有值
        return proxy.$setting.globalUrl.upload+'/'+fileUrl.value
    }
    return ""
})
let isImg = computed(() => {
    if(obj.fileUrl == "") return false;
    return ['jpg','jpeg','png','gif'].some(t => t == obj.fileUrl.split('.').pop().toLowerCase())
})
watch(
    () => props.file,
    (val) => obj.fileUrl = props.file
)

let del = () => {
    obj.fileUrl = ""
    emit('update:file', "")
}
let upfile = e =>{
    // console.log(e);
    let file = e.srcElement.files[0]
    if (!file) return //用户点了取消，会触发这个，加上这个判断，就不会继续了
    if (props.debug) console.log(file.type)
    const isType = props.accept.some(t => t === file.type)
    const isLimit = file.size < props.maxsize

    // obj.isImg = ['image/jpeg','image/png','image/gif'].some(t => t === file.type)

    if (!isType) {
        proxy.elMessageMixin(`只能上传${props.accept.join(',')}格式`, 'error')
        return
    }
    if (!isLimit) {
        proxy.elMessageMixin(`不能超过${props.maxsize/file.size}M`, 'error')
        return
    }

    //检查完成，可以上传
    let formData = new FormData(); //这样可以给form参数了
    formData.append("type", file.type);
    formData.append("file", file);
    if (props.maxwidth > 0) formData.append("maxheight", props.maxwidth);
    if (props.maxheight > 0) formData.append("maxwidth", props.maxheight);
    if (props.background != "") formData.append("background", props.background);

    proxy.$ajax({
        baseURL: "",
        url: proxy.$setting.globalUrl.uploadserver,
        data: formData,
        isUploadFile: true,
        bfLoading: false,
        timeout: 0,
        progress: p => {
            obj.progressFlag = true
            obj.loadProgress = (p.loaded / p.total * 100 | 0) + '%'
        }
    }).then(res => {
        isUpload = true
        obj.fileUrl = res.filename
        emit('update:file', res.filename)
        emit('upload',res.filename)
        obj.progressFlag = false
    }).catch((() => obj.progressFlag = false))
}

let { fileUrl,progressFlag,loadProgress } = toRefs(obj)
</script>

<style lang="scss" scoped>
    $w: 120px;
    $h: 120px;
    $color: #d8dae2;
    .up { position: relative; width: $w; height: $h+20; overflow: hidden; }
    .up_del { position: absolute; top: 0; right: 6px; }
    .up_del::after { content: "\e627"; font-family: "iconfont"; font-size: 10px; }
    .up input { position: absolute; top:-20px; font-size:0; -webkit-appearance:none; width: $w; height: $h+20; }
    .avatar { position: absolute; width: $w; height: $h; object-fit: contain; box-sizing: border-box; border: 1px solid $color; }
    .avatar-uploader-file::after { content:'\e6b7'; font-family: "iconfont"; font-size: 40px; }
    .avatar-uploader,.avatar-uploader-file { width: $w; height: $h; background-color: #FFF; border: 1px solid $color; box-sizing: border-box; display: flex; justify-content: center; align-items: center; }
    .avatar-uploader::after { content:'\e603'; font-family: "iconfont"; font-size: 40px; color: $color; }
    .progress { position:absolute; bottom:0; display: flex; width:120px; margin-top: 3px; align-items: center; }
    .progress * { display: flex; font-style: normal; font-size: 12px; }
    .progress span { flex: 1; align-items: center; height:6px; border-radius: 3px; background-color: $color; margin-right: 5px; }
    .progress u { background-color: #3a4fbd; height:6px; border-radius: 3px;  }
    .up-file{
        position: relative;height: 30px; width: 60px; overflow: hidden;line-height: 30px;text-align: center;
        display: inline-block; cursor: pointer; font-size: 14px; border-radius: 6px; background-color: #0070CC; color: #FFFFFF;margin-right: 10px;
    }

    .up-file  input{
        position: absolute;height: 30px; width: 60px; top:0px; left:0; font-size:0; -webkit-appearance:none;opacity: 0;cursor: pointer;
    }
</style>